import { defineStore } from 'pinia';
import type { UserState } from './types';
import {
  getProfile,
  sendCode,
  login as userLogin,
  logout as userLogout,
} from '@/api/user/index';
import type { LoginParams } from '@/api/user/types';
import { clearToken, setToken } from '@/utils/auth';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: '',
    userName: '雨果',
    userAccount: '',
    mobile: '',
    status: '',
    gender: '',
    genderName: '',
    courseHours: 0,
    usedHours: 0,
    fromVip: '',
  }),
  getters: {},
  actions: {
    // 设置用户的信息
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },
    // 重置用户信息
    resetInfo() {
      this.$reset();
    },
    // 获取用户信息
    async info() {
      const result = await getProfile();
      if (!result)
        return false;
      this.setInfo(result);
      return true;
    },
    // 异步登录并存储token
    login(loginForm: LoginParams) {
      return new Promise((resolve, reject) => {
        userLogin(loginForm).then((res) => {
          const token = res.token;
          if (token) {
            setToken(token);
          }
          resolve(res);
        }).catch((error) => {
          uni.showToast({
            icon: 'error',
            title: error.msg,
          });
          reject(error);
        });
      });
    },
    // Logout
    async logout() {
      await userLogout();
      this.resetInfo();
      clearToken();
    },
    // 发送验证码
    getCode(target: string) {
      return new Promise((resolve) => {
        sendCode({ target }).then(() => {
          uni.showToast({
            icon: 'success',
            title: '发送成功',
          });
          resolve(true);
        }).catch((err) => {
          uni.showToast({
            icon: 'error',
            title: err.messageq,
          });
          resolve(true);
        });
      });
    },

    // 小程序授权登录
    // authLogin(provider: providerType = 'weixin') {
    //   return new Promise((resolve, reject) => {
    //     uni.login({
    //       provider,
    //       success: async (result: UniApp.LoginRes) => {
    //         if (result.code) {
    //           const res = await loginByCode({ code: result.code });
    //           resolve(res);
    //         }
    //         else {
    //           reject(new Error(result.errMsg));
    //         }
    //       },
    //       fail: (err: any) => {
    //         console.error(`login error: ${err}`);
    //         reject(err);
    //       },
    //     });
    //   });
    // },
  },
});

export default useUserStore;
